package com.sam;

import android.util.Log;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TCPClient {

	private String serverMessage;
	public static final String SERVERIP = "192.168.184.1";
	public static final int SERVERPORT = 8080;
	private static OnMessageReceived mMessageListener = null;
	private boolean mRun = false;
	protected static TCPClient mInstance;

	ObjectOutputStream oos = null;
	ObjectInputStream ois = null;

	private TCPClient() {

	}

	public static TCPClient getInstance(OnMessageReceived listener) {
		if (mInstance == null) {
			mMessageListener = listener;
			mInstance = new TCPClient();

		}
		return mInstance;
	}

	public void sendMessage(DataStream data) {

		if (data == null)
			;
		else if (oos != null) {
			try {
				oos.writeObject(data);
				oos.flush();
				String message = data.getmessage();
				Log.i("Msg 4m Client", message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public void stopClient() {
		mRun = false;
	}

	public void run() {

		mRun = true;

		try {
			// here you must put your computer's IP address.
			InetAddress serverAddr = InetAddress.getByName(SERVERIP);

			Log.e("TCP Client", "C: Connecting...");

			// create a socket to make the connection with the server
			Socket socket = new Socket(serverAddr, SERVERPORT);

			try {

				// send the message to the server
				oos = new ObjectOutputStream(socket.getOutputStream());
				String message = "Cnone";
				oos.writeObject(new DataStream(message, null, null));
				Log.e("TCP Client", "C: Sent.");

				Log.e("TCP Client", "C: Done.");

				// receive the message which the server sends back
				ois = new ObjectInputStream(socket.getInputStream());

				// in this while the client listens for the messages sent by the
				// server
				while (mRun) {

					DataStream data = (DataStream) ois.readObject();

					if (data != null && mMessageListener != null) {
						String mess = data.getmessage();
						Log.i("Msg 4m Ser", mess);

						// call the method messageReceived from ServerBoard
						// class
						mMessageListener.messageReceived(data);
					}
				}

				Log.e("RESPONSE FROM SERVER", "S: Received Message: '"
						+ serverMessage + "'");

			} catch (Exception e) {

				Log.e("TCP", "S: Error", e);

			} finally {
				// the socket must be closed. It is not possible to reconnect to
				// this socket
				// after it is closed, which means a new socket instance has to
				// be created.
				socket.close();
			}

		} catch (Exception e) {

			Log.e("TCP", "C: Error", e);

		}

	}

	// Declare the interface. The method messageReceived(String message) will
	// must be implemented in the MyActivity
	// class at on asynckTask doInBackground
	public interface OnMessageReceived {
		public void messageReceived(DataStream data);
	}
}